package com.davy.tx;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatButton;


import com.alibaba.fastjson.JSON;
import com.davy.tx.http.CommonHttpConsts;
import com.davy.tx.http.HttpCallbackData;
import com.davy.tx.http.HttpClient;
import com.davy.tx.utils.CryptoTools;
import com.davy.tx.utils.DialogUitl;
import com.davy.tx.utils.LogUtils;
import com.davy.tx.utils.SPUtils;
import com.davy.tx.utils.StringUtils;
import com.davy.tx.utils.ToastUtil;

import java.util.Map;

public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private long mExitTime = 0;//退出程序
    private AppCompatButton login_btn, face_login_btn, regist_btn, init_btn;
    private ImageView imgMima, imgEye;
    private LinearLayout lyMima;
    private String userPhone, password;
    private EditText ed_userPhone, ed_password;
    private boolean isMima = false;
    private boolean isEye = false;
    private boolean isType;
    private RelativeLayout lyRelative;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(mContext)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + mContext.getPackageName()));
                startActivityForResult(intent, 1001);
            }
        }
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
//            if (!Environment.isExternalStorageManager()) {
//                Intent appIntent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
//                appIntent.setData(Uri.parse("package:" + getPackageName()));
//                try {
//                    mContext.startActivity(appIntent);
//                } catch (ActivityNotFoundException ex) {
//                    ex.printStackTrace();
//                    Intent allFileIntent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
//                    mContext.startActivity(allFileIntent);
//                }
//            }
//        }
    }

    private void initView() {
        imgEye = findViewById(R.id.imgEye);
        lyMima = findViewById(R.id.lyMima);
        imgMima = findViewById(R.id.imgMima);
        login_btn = findViewById(R.id.login_btn);
        ed_userPhone = findViewById(R.id.ed_userPhone);
        ed_password = findViewById(R.id.ed_password);
        init_btn = findViewById(R.id.init_btn);
        regist_btn = findViewById(R.id.regist_btn);
        face_login_btn = findViewById(R.id.face_login_btn);
        lyRelative = findViewById(R.id.lyRelative);

        lyMima.setOnClickListener(this);
        login_btn.setOnClickListener(this);
        init_btn.setOnClickListener(this);
        regist_btn.setOnClickListener(this);
        face_login_btn.setOnClickListener(this);
        lyRelative.setOnClickListener(this);

        userPhone = SPUtils.get(mContext, "userPhone", "") + "";
        password = SPUtils.get(mContext, "password", "") + "";
        isType = (Boolean) SPUtils.get(mContext, "isType", false);

        if (!StringUtils.isEmpty(userPhone)) {
            ed_userPhone.setText(userPhone);
        }

        if (isType) {
            isMima = true;
            imgMima.setBackground(getResources().getDrawable(R.mipmap.mima_seletd));
            if (!StringUtils.isEmpty(password)) {
                ed_password.setText(password);
            }
        } else {
            isMima = false;
            imgMima.setBackground(getResources().getDrawable(R.mipmap.mima));
        }

        imgEye.setOnClickListener(v -> {
            if (isEye) {
                isEye = false;
                ed_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                imgEye.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.icon_eye_b));
            } else {
                isEye = true;
                ed_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                imgEye.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.icon_eye_z));
            }
        });
    }

    @SuppressLint("NewApi")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lyMima:
                if (isMima) {
                    isMima = false;
                    imgMima.setBackground(getResources().getDrawable(R.mipmap.mima));
                } else {
                    isMima = true;
                    imgMima.setBackground(getResources().getDrawable(R.mipmap.mima_seletd));
                }
                break;

            case R.id.login_btn:
                userPhone = ed_userPhone.getText().toString().trim();
                if (StringUtils.isEmpty(userPhone)) {
                    ToastUtil.show("请输入手机号!");
                    return;
                }
                password = ed_password.getText().toString().trim();
                if (TextUtils.isEmpty(password)) {
                    ToastUtil.show("请输入密码!");
                    return;
                }
                if (StringUtils.isFastClick()) {
                    return;
                }

                loginData();
                break;
            case R.id.lyRelative:
                StringUtils.hintKeyBoard(mContext, lyRelative);
                break;
        }
    }

    public void onRegisterClick(View v) {
//        Intent intent = new Intent(mContext, RegisterActivity.class);
//        startActivity(intent);
    }

    private void loginData() {
        String encryTel = "";
        String encryPwd = "";
        try {
            encryTel = CryptoTools.base64Encode(userPhone);
            encryPwd = CryptoTools.base64Encode(password);

            LogUtils.e("TAG", "encrypt:" + encryTel);
            LogUtils.e("TAG", "encrypt:" + encryPwd);
            LogUtils.e("TAG", "base64Decode---:" + CryptoTools.base64Decode(encryTel));
            LogUtils.e("TAG", "base64Decode----:" + CryptoTools.base64Decode(encryPwd));
        } catch (Exception e) {
            e.printStackTrace();
        }

        HttpClient.getInstance().getData(CommonHttpConsts.login, "login")
                .params("encryTel", encryTel)
                .params("encryPwd", encryPwd)
                .execute(new HttpCallbackData() {

                    @Override
                    public void onError() {
                        super.onError();
                        ToastUtil.show("网络异常请稍后再试！");
                    }

                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        if (code == 200) {
                            if (!StringUtils.isEmpty(info)) {
                                String string = StringUtils.decompressForGzip(info);
                                LogUtils.e("TAG", "string:" + string);
                                if (!StringUtils.isEmpty(string)) {
                                    Map dataMap = JSON.parseObject(string);

                                    SPUtils.put(mContext, "isType", isMima);
                                    SPUtils.put(mContext, "userPhone", dataMap.get("Phone") + "");
                                    SPUtils.put(mContext, "userName", dataMap.get("UserName") + "");
                                    SPUtils.put(mContext, "password", dataMap.get("Pwd") + "");
                                    SPUtils.put(mContext, "token", dataMap.get("Token") + "");//登录token

                                    SPUtils.put(mContext, "BelongPwsName", dataMap.get("BelongPwsName") + "");
                                    SPUtils.put(mContext, "PwsName", dataMap.get("PwsName") + "");
                                    SPUtils.put(mContext, "CjName", dataMap.get("CjName") + "");
                                    SPUtils.put(mContext, "GqName", dataMap.get("GqName") + "");
                                    SPUtils.put(mContext, "jobName", dataMap.get("JobName") + "");
                                    SPUtils.put(mContext, "Company", dataMap.get("Company") + "");
                                    SPUtils.put(mContext, "Module", dataMap.get("Module") + "");
                                    SPUtils.put(mContext, "Type", dataMap.get("Type") + "");
                                    SPUtils.put(mContext, "JobId", dataMap.get("JobId") + "");
                                    SPUtils.put(mContext, "GqId", dataMap.get("GqId") + "");
                                    SPUtils.put(mContext, "CjId", dataMap.get("CjId") + "");
                                    SPUtils.put(mContext, "PwsId", dataMap.get("PwsId") + "");
                                    SPUtils.put(mContext, "Face", dataMap.get("Face") + "");

                                    if (StringUtils.isEmpty(dataMap.get("UserName") + ""))
                                        SPUtils.remove(mContext, "userName");

                                    if (StringUtils.isEmpty(dataMap.get("BelongPwsName") + ""))
                                        SPUtils.remove(mContext, "BelongPwsName");

                                    if (StringUtils.isEmpty(dataMap.get("PwsName") + ""))
                                        SPUtils.remove(mContext, "PwsName");

                                    if (StringUtils.isEmpty(dataMap.get("CjName") + ""))
                                        SPUtils.remove(mContext, "CjName");

                                    if (StringUtils.isEmpty(dataMap.get("GqName") + ""))
                                        SPUtils.remove(mContext, "GqName");

                                    if (StringUtils.isEmpty(dataMap.get("JobName") + ""))
                                        SPUtils.remove(mContext, "jobName");

                                    if (StringUtils.isEmpty(dataMap.get("Company") + ""))
                                        SPUtils.remove(mContext, "Company");

                                    if (StringUtils.isEmpty(dataMap.get("Module") + ""))
                                        SPUtils.remove(mContext, "Module");

                                    if (StringUtils.isEmpty(dataMap.get("Type") + ""))
                                        SPUtils.remove(mContext, "Type");

                                    if (StringUtils.isEmpty(dataMap.get("JobId") + ""))
                                        SPUtils.remove(mContext, "JobId");

                                    if (StringUtils.isEmpty(dataMap.get("GqId") + ""))
                                        SPUtils.remove(mContext, "GqId");

                                    if (StringUtils.isEmpty(dataMap.get("CjId") + ""))
                                        SPUtils.remove(mContext, "CjId");

                                    if (StringUtils.isEmpty(dataMap.get("PwsId") + ""))
                                        SPUtils.remove(mContext, "PwsId");

                                    if (StringUtils.isEmpty(dataMap.get("Face") + ""))
                                        SPUtils.remove(mContext, "Face");


                                    String dateTime = StringUtils.getTimeS();
                                    SPUtils.put(mContext, "userType", true);
                                    SPUtils.put(mContext, "dateTime", dateTime);
                                    startActivity(new Intent(mContext, MainActivity.class));
                                    finish(); // 结束当前Activity
                                } else {
                                    ToastUtil.show(msg);
                                }
                            }
                        } else {
                            ToastUtil.show(msg);
                        }
                    }

                    @Override
                    public boolean showLoadingDialog() {
                        return true;
                    }

                    @Override
                    public Dialog createLoadingDialog() {
                        return DialogUitl.loginAuthDialog(mContext);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                ToastUtil.show("再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                ScreenManager.getScreenManager().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
